<?php

namespace App\Models;


use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * @method static Administrator|null find($userId)
 */
class Administrator extends \Dcat\Admin\Models\Administrator
{

    protected $fillable = [
        "username",
        "password",
        "name",
        "avatar",
        "online",
        "dispatch_limit",
    ];

    public static $dispatchDateKey = '_pre_dispatch_';

    public function baseForm()
    {
        return $this->belongsToMany(XXlBaseForm::class, 'admin_user_has_test_form', 'user_id', 'form_id');
    }

    public function group()
    {
        return $this->belongsToMany(UserGroup::class, 'groups_has_user', 'user_id', 'group_id');
    }

    public static function getDispatchUserList($query = 'pluck')
    {
        $q = Administrator::query()
            ->whereHas('roles', function ($query) {
                $query->where('slug', 'base_form_dispatch');
            });
        switch ($query) {
            case "pluck":
                return $q->get()->pluck('name', 'id');
            default:
                return $q;
        }
    }

    public function userGetOne($key)
    {
        Cache::increment($key);
        Cache::put($this->id . Administrator::$dispatchDateKey, Carbon::now()->toDateTimeString(), 60 * 60 * 24);
    }

    public function userForgetOne($key)
    {
        $val = (int)Cache::get($key);

        if ($val > 0) {
            Cache::decrement($key);
        }

    }


    public function isOnline()
    {
        return !!$this->online;
    }
}
